﻿using Prism.Commands;
using Prism.Dialogs;
using Prism.Mvvm;
using Rafy.Domain;
using SwaggerSdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

namespace Rafy.Book.ViewModels
{
    public class FmWordViewModel : BindableBase, IDialogAware
    {
        private readonly ApiClient _apiClient;
        private string _wordInput;
        public string WordInput
        {
            get => _wordInput;
            set => SetProperty(ref _wordInput, value);
        }
        public int cataId { get; set; }
        public int bookId { get; set; }

        public DelegateCommand SaveCommand { get; }
        public FmWordViewModel(ApiClient apiClient)
        {
            _apiClient = apiClient;
            SaveCommand = new DelegateCommand(async () => await OnSave());
        }

        private async Task OnSave()
        {
            Console.WriteLine($"保存字词：{WordInput},{WordInput.Split(' ').Length}");
            if (string.IsNullOrEmpty(WordInput))
            {
                HandyControl.Controls.Growl.Warning("文本框内容不能为空", "InfoMessage");
                return;
            }
            else
            {
                var words = WordInput.Split(' ');
                foreach (var word in words)
                {
                    if(!string.IsNullOrEmpty(word))
                    {
                       
                        if (word.Length == 1)
                        {
                            await SaveWord(word);
                        }
                        else
                        {
                            await SaveWords(word);
                        }
                    }
                }
            }
            RequestClose.Invoke(new DialogResult(ButtonResult.OK));
        }

        private async Task SaveWords(string words)
        {
            var repo = RF.ResolveInstance<YuWen_BookWordsRepository>();
            var obj = repo.GetBy(bookId, cataId, words);
            //在图书目录中查找是否存在
            if (obj == null)
            {
                var rp = RF.ResolveInstance<YuWen_WordsRepository>();
                var wordObj = rp.GetByWords(words);
                if (wordObj == null)//到字典是去查询
                {
                    var model = await _apiClient.GetWordsHtml(words);
                    wordObj = SaveModelWords(model);
                }

                if(wordObj!=null && wordObj.Id > 0)
                {
                    //现在库中有了，保存到图书目录中
                    obj = new YuWen_BookWords();
                    obj.F_BookId = bookId;
                    obj.F_CatalogId = cataId;
                    obj.F_UserId = 0;
                    obj.ShowPinyin = true;
                    obj.F_WordsId = wordObj.Id;
                    repo.Save(obj);
                }               
            }
        }

        private YuWen_Words SaveModelWords(RspWords m)
        {
            var repo = RF.ResolveInstance<YuWen_WordsRepository>();
            YuWen_Words obj = new YuWen_Words();
            obj.F_Name = m.F_Name;
            obj.F_PinYin = m.F_PinYin;
            obj.F_NameLen = m.F_Name.Length;
            obj.F_CiXing = m.F_CiXing;
            obj.F_GanQing = m.F_GanQing;
            obj.F_FanTi = m.F_FanTi;
            obj.F_JinYiCi = m.F_JinYiCi;
            obj.F_FanYiCi = m.F_FanYiCi;
            obj.F_JieShi = m.F_JieShi;
            obj.F_FaYin = m.F_FaYin;
            obj.F_Pic = m.F_Pic;
            obj.F_Video= m.F_Video;
            obj.F_Url = m.F_Url;
            obj.F_Html = m.F_Html;
            repo.Save(obj);
            return obj;
        }

        #region 保存汉字
        /// <summary>
        /// 保存汉字
        /// </summary>
        private async Task SaveWord(string keyword)
        {
            string word = keyword.Trim();
            var repo = RF.ResolveInstance<YuWen_BookWordRepository>();
            var obj = repo.GetBy(bookId, cataId, word);
            //在图书目录中查找是否存在
            if (obj == null)
            {
                var rp = RF.ResolveInstance<YuWen_WordRepository>();
                var wordObj = rp.GetByName(word);
                if (wordObj == null)//表中不存在到网络抓取
                {
                    var model = await _apiClient.GetWordHtml(word);
                    wordObj = SaveModelWord(model);
                }
                //现在库中有了，保存到图书目录中
                if (wordObj != null && wordObj.Id > 0)
                {
                    obj = new YuWen_BookWord();
                    obj.F_BookId = bookId;
                    obj.F_CatalogId = cataId;
                    obj.F_UserId = 0;
                    obj.ShowPinyin = true;
                    obj.F_WordId = wordObj.Id;
                    repo.Save(obj);
                }
            }

        }

        private YuWen_Word SaveModelWord(RspWord m)
        {
            var repo = RF.ResolveInstance<YuWen_WordRepository>();
            YuWen_Word obj = new YuWen_Word();
            obj.F_Name = m.F_Name;
            obj.F_PinYin = m.F_PinYin;
            obj.F_BuShou = m.F_BuShou;
            obj.F_ZongBiHua = m.F_ZongBiHua;
            obj.F_BiHua = m.F_BiHua;
            obj.F_JieGou = m.F_JieGou;
            obj.F_JieShi = m.F_JieShi;
            obj.F_JinYiCi = m.F_JinYiCi;
            obj.F_FanYiCi = m.F_FanYiCi;
            obj.F_ChaiZi = m.F_ChaiZi;
            obj.F_Url = m.F_Url;
            obj.F_Html = m.F_Html;
            repo.Save(obj);
            return obj;
        } 
        #endregion


       





        public string Title => "添加字词";


        public DialogCloseListener RequestClose { get; }

        //这个方法是允许关闭窗口
        public bool CanCloseDialog()
        {
            return true;
        }
        //关闭方法
        public void OnDialogClosed()
        {
            //RequestClose.Invoke(ButtonResult.Cancel);
            //MessageBox.Show("关闭窗口");
        }
        //打开之前传递过来的参数
        public void OnDialogOpened(IDialogParameters parameters)
        {
            //从上页面中传过来的参数
            cataId = parameters.GetValue<int>("cataId");
            bookId = parameters.GetValue<int>("bookId");
            Console.WriteLine($"cataId={cataId} bookid={bookId}");
           
        }
    }
}
